
// 对request的 上层封装
const rp = require('request-promise-native')

const mongoose = require('mongoose')
const Movie = mongoose.model('Movie')
const Category = mongoose.model('Category')

// 用户 获取 当前电影的 相关信息
async function fetchMovie(item) { 
  const url = `https://api.douban.com/v2/movie/${item.doubanId}?apikey=0b2bdeda43b5688921839c8ecb20399b`

  let res = await rp(url)

  try {
    res = JSON.parse(res)
  } catch(e) {
    console.log(e)
    res = null
  }
  return res
}

;(async () => {
  
  // 查找 当前需要更新的 电影
  let movies = await Movie.find({
    $or: [
      { summary: { $exists: false }}, // 没有 summar字段
      { summary: null },
      { year: { $exists: false }},
      { title: '' },
      { summary: '' }
    ]
  })
  // 遍历
  for (let i = 0; i < movies.length; i++) {
    let movie = movies[i]
    // 获取当前 电影的 相关信息
    let movieData = await fetchMovie(movie)

    // 获取成功
    if (movieData) {
      let tags = movieData.tags || []

      // 赋值操作
      movie.tags = movieData.tags || []
      movie.summary = movieData.summary || ''
      movie.title = movieData.alt_title || movieData.title || ''
      movie.rawTitle = movieData.title || ''

      if ( movieData.attrs ) {
        movie.year = movieData.attrs.year[0] || 2500
        // 电影的 分类信息
        movie.movieTypes = movieData.attrs.movie_type || []
        // [ "剧情", "动画" ]遍历
        for (let i = 0; i < movie.movieTypes.length; i++) {
          let item = movie.movieTypes[i]
          // 分类
          let cat = await Category.findOne({ // 查找 是否有当前类别
            name: item
          })

          if (!cat) { // 没有则创建 当前的 分类
            cat = new Category({
              name: item,
              movies: [movie._id]
            })
          } else { // 有当前 分类 则把 当前电影的id 存储在此分类下
            if (cat.movies.indexOf(movie._id) === -1) {
              cat.movies.push(movie._id)
            }
          }

          // 更新
          await cat.save()

          // 电影数据 更新数据
          if (!movie.category) { // 没有
            movie.category.push(cat._id)
          } else {
            if (movie.category.indexOf(cat._id) === -1) {
              movie.category.push(cat._id)
            }
          }
        } 

        let dates = movieData.attrs.pubdate || []
        let pubdates = []

        dates.map(item => {
          if (item && item.split('(').length > 0) {
            let parts = item.split('(')
            let date = parts[0]

            let country = '未知'
            if (parts[1]) {
              country = parts[1].replace(')', '')
            }

            pubdates.push({
              date: new Date(date),
              country
            })
          }
        })

        movie.pubdate = pubdates    
      }

      tags.forEach( tag => {
        movie.tags.push(tag.name)
      })

      // 同步
      await movie.save()
    }
  }
})()